package com.corpgovernment.common.localcache;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * @program: parent
 * @description: 本地缓存基类
 * @author: wubing
 * @create: 2019-11-05 20:49
 */
@Slf4j
public abstract class BaseLocalCache<K, V> {

    private LoadingCache<K, V> cache = CacheBuilder.newBuilder().expireAfterWrite(expireTimeSecond(), TimeUnit.SECONDS).build(new CacheLoader<K, V>() {
        @Override
        public V load(K k) {
            log.info("guava缓存key:{}失效，初始化缓存********************", k);
            return loadVal(k);
        }
    });

    /**
     * 无参构造
     */
   /* public BaseLocalCache() {
        cache = CacheBuilder.newBuilder().build(new CacheLoader<K, V>() {
            @Override
            public V load(K k) throws Exception {
                return loadVal(k);
            }
        });
    }
*/

    /**
     * 无参构造
     */
   /* public BaseLocalCache(long duration, TimeUnit timeUnit) {
        cache = CacheBuilder.newBuilder().expireAfterWrite(duration, timeUnit).build(new CacheLoader<K, V>() {
            @Override
            public V load(K k) {
                log.info("guava缓存key:{}失效，初始化缓存********************", k);
                return loadVal(k);
            }
        });
    }*/

    /**
     * 实现缓存加载方式
     *
     * @param k
     * @return
     */
    protected abstract V loadVal(K k);

    /**
     * 超时秒
     * @return
     */
    protected abstract int expireTimeSecond();


    /**
     * 获取缓存
     *
     * @param k
     */
    public V getCache(K k) throws ExecutionException {
        V v = cache.get(k);
        log.info("guava获取本地缓存，key:{},value:{}********************", k);
        return v;
    }
}